package com.oweight.sagacious.auth.server.domain.service.spring;

import com.oweight.sagacious.api.model.user.PersonInfo;
import com.oweight.sagacious.auth.common.util.jwt.JWTInfo;
import com.oweight.sagacious.auth.server.domain.service.IClientManager;
import com.oweight.sagacious.auth.server.infrastructure.util.user.JwtAuthenticationRequest;
import com.oweight.sagacious.auth.server.infrastructure.util.user.JwtTokenUtil;
import com.oweight.sagacious.auth.server.infrastructure.util.user.WeChatLoginForm;
import com.oweight.sagacious.auth.server.interfaces.feign.OrganizationService;
import com.oweight.sagacious.common.exception.auth.UserInvalidException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 周广明
 * @version v1 2019/10/30 14:03
 */
@Slf4j
@Service
public class ClientManager implements IClientManager {

    private JwtTokenUtil jwtTokenUtil;
    private OrganizationService userService;

    @Autowired
    public ClientManager(
            JwtTokenUtil jwtTokenUtil,
            OrganizationService userService) {
        this.jwtTokenUtil = jwtTokenUtil;
        this.userService = userService;
    }

    @Override
    public String login(JwtAuthenticationRequest authenticationRequest) throws Exception {
        try {
            PersonInfo info = userService.validate(authenticationRequest);
            if (info != null) {
                // 返回用户信息Token
                return jwtTokenUtil.generateToken(new JWTInfo(info.getUsername(), info.getId(), info.getName()));
            } else {
                throw new UserInvalidException("用户不存在或账户密码错误!");
            }
        } catch (Exception e) {
            throw new UserInvalidException("服务端生成Token失败！\n" + e.getLocalizedMessage());
        }
    }

    @Override
    public String login2(WeChatLoginForm form) throws Exception {
        try {
            PersonInfo info = userService.validate(form);
            if (info != null) {
                // 返回用户信息Token
                return jwtTokenUtil.generateToken2(info);
            } else {
                throw new UserInvalidException("用户不存在或账户密码错误!");
            }
        } catch (Exception e) {
            throw new UserInvalidException("服务端生成Token失败！\n" + e.getLocalizedMessage());
        }
    }

    @Override
    public void validate(String token) throws Exception {
        jwtTokenUtil.getInfoFromToken(token);
    }

    @Override
    public String refresh(String oldToken) throws Exception {
        return jwtTokenUtil.generateToken(jwtTokenUtil.getInfoFromToken(oldToken));
    }
}
